package cm.utils;

import cm.exception.ServiceExceptionUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.UUID;

import static cm.exception.ErrorCodeConstants.ERROR_CODE_MESSAGE;

/**
 * @author: yxh
 * @Description: 文件转换
 * @Date: Created in 2023/3/16 11:28
 * @Modified By:
 */
public class FileTransformationUtil {

    public static File FileToMultipartFile(MultipartFile multipartFile,String path){
        File file = new File(path);
        try {
            //获取文件名
            String fileName = multipartFile.getOriginalFilename();
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            //重新生成文件名
            fileName = UUID.randomUUID() + suffixName;
            FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), file);
            return file;
        }catch (Exception e){
            throw ServiceExceptionUtil.exception(ERROR_CODE_MESSAGE);
        }
    }

    public static MultipartFile FileToMultipartFile(File file){
        try {
            InputStream inputStream = new FileInputStream(file);
            MultipartFile multipartFile = new MockMultipartFile(file.getName(), inputStream);
            return multipartFile;
        }catch (Exception e){
            throw ServiceExceptionUtil.exception(ERROR_CODE_MESSAGE);
        }

    }
}
